<template>
  <div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
      <div class="table-page-search-wrapper">
        <a-form :form="searchForm" layout="inline">
          <a-row :gutter="48">
            <SearchFormItems
              :searchKeys="FundListSearchKeys"
              :getDataWithKey="getDataWithKey"
            >
            </SearchFormItems>
            <a-col :md="6" :sm="6" class="advanced_butns">
              <span
                class="table-page-search-submitButtons"
              >
                <a-button type="primary" @click="search">搜索</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" :loading="exportLoading" @click="exportExcel('normal')">导出余额</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div class="cont_box">
      <div class="table_header flex-between">
        <div class="table_name">{{ pageTitle }}</div>
        <div class="table_butns flex-end">
          <a-button type="primary" icon="plus" @click="showModal('add', null)">新增</a-button>
          <!-- <a-button :loading="balanceLoading" :disabled="selectedRowKeys.length == 0" @click="exportExcel('balance')">导出余额</a-button> -->
        </div>
      </div>
      <a-table
        :columns="FundListColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it,index) => it.id + index"
        :loading="loading"
        :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
        }"
        binvested
        @change="tableSort"
      >
        <span slot="operation" slot-scope="text, record">
          <a-button size="small" type="link" @click="showModal('edit', record)">编辑</a-button>
          <a-button size="small" type="link" @click="showModal('record',record)">补录</a-button>
          <a-button size="small" type="link" @click="goFlowDetail(record)">资金明细</a-button>
        </span>
      </a-table>
      <pagination
        :total="total"
        :page.sync="page"
        :size.sync="size"
        :onPageSizeChange="onPageSizeChange" 
        :onShowSizeChange="onShowSizeChange" 
      />
      <a-modal
        :title="modalType == 'edit' ? '编辑' : '新增'"
        v-model="editVisible"
        destroyOnClose
        @ok="sureModal"
        width="600px"
      >
        <div class="modal_body_cont">
          <a-form
            :form="modalForm"
            :label-col="{ span: 7 }"
            :wrapper-col="{ span: 15 }"
          >
            <modalFormItem
              :searchKeys="FundListModalKeys"
              :getDataWithKey="getDataWithKey"
              :onSwitchChange ="onSwitchChange"
            ></modalFormItem>
          </a-form>
        </div>
      </a-modal>
      <a-modal
        title="资金补录"
        v-model="addRecordVisible"
        destroyOnClose
        @ok="sureAddRecord"
        width="600px"
      >
        <div class="modal_body_cont">
          <a-form
            :form="modalForm2"
            :label-col="{ span: 7 }"
            :wrapper-col="{ span: 15 }"
          >
            <modalFormItem
              :searchKeys="FundListAddKeys"
              :getDataWithKey="getDataWithKey"
              :onSwitchChange ="onSwitchChange"
            ></modalFormItem>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { CurrencyTypes,AddRecordTypes,PayChannel,resetBillType} from '../../utils/constant.js'
import { FundListSearchKeys, FundListColumn, FundListModalKeys,FundListAddKeys } from "./config";
import { capitalClientList,capitalList,capitalAdd,capitalEdit,capitalAddRecord,exportCapitalList } from "@/api/capital";

export default {
  name: "FundList",
  data() {
    return {
      clientArrays:[],
      pageTitle: "",
      FundListSearchKeys,
      FundListColumn,
      FundListModalKeys,
      FundListAddKeys,
      dataSource: [],
      pagination: false,
      page: 1,
      size: 50,
      total: 0,
      loading: false,
      selectedRowKeys:[],
      exportLoading:false,
      balanceLoading:false,
      searchForm: this.$form.createForm(this, { name: "fund_list_search" }),
      editVisible: false,
      modalForm: this.$form.createForm(this, { name: "fund_list_modal" }),
      modalForm2: this.$form.createForm(this,{ name:'fund_modal_add' }),
      addRecordVisible:false,
      
      capitalId: "",
      importLoading: false,
      modalType: "add",
      sortString: "",
      generateFileTypeOpt: [],
      companyStatusEnumOpt: [],
    };
  },
  computed: {
    getDataWithKey() {
      return (key) => {
        switch (key) {
          case "currencyType":
            return CurrencyTypes ;
          case "clientId":
            return this.clientArrays;
          case "employeeName":
            return this.clientArrays;
          case "addedType":
            return AddRecordTypes;
          case "channel":
            return PayChannel;
          case "type":
            return resetBillType;
          default:
            return [];
        }
      };
    },
  },
  created() {
    this.pageTitle = this.$route?.meta?.title;
    this.getClientList()
    this.getList();
  },
  methods: {
    async getClientList(){
      let res = await capitalClientList({pageNum: 1, pageSize: 1000}),temList = res?.data || [],
      list = []
      console.log('client  list',res)
      for(let i = 0;i<temList.length;i++){
        let temObj = {
          key:temList[i].id,
          value:temList[i].name
        }

        list.push(temObj)
      }
      this.clientArrays = list
    },
    search() {
      this.page = 1;
      this.getList();
    },
    reset() {
      this.searchForm.resetFields();
      this.page = 1;
      this.getList();
    },
    onPageSizeChange(page, size) {
      this.selectedRowKeys = []
      this.page = page;
      this.getList(page, size);
    },
    onShowSizeChange(page, size){
      this.selectedRowKeys = []
      this.page = page;
      this.size = size;
      this.getList(page, size);
    },
    onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
    },
    exportExcel(type){
      if(type == 'normal'){
        this.searchForm.validateFields(async (err, values) => {
          if(!values?.clientId){
            this.$message.error('请在搜索框选择客户，再进行导出余额操作！')
            return
          }
          if (!err) {
            this.exportLoading = true
            let params = {
              ...values,
            };
            const res = await exportCapitalList(params);
            console.log('rrrr',res)
            const link = document.createElement("a"); // 创建a标签
              let blob = new Blob([res], {
                type: "application/vnd.ms-excel;charset=UTF-8",
              }); // 设置文件类型
              link.style.display = "none";
              link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
              link.setAttribute("download", '账户列表');//文件名，而不是写死.excel之类
              document.body.appendChild(link);//创建
              link.click();//点击事件
              document.body.removeChild(link);
            this.exportLoading = false
          }
          this.exportLoading = false
        });
      }
      
    },
    onSwitchChange(type){
      console.log('dddd',type)
    },

    statusUpdate(record) {
      this.$confirm({
        title: `确定要${record.status == "正常" ? "禁用" : "启用"}吗？`,
        content: "",
        okText: `${record.status == "正常" ? "禁用" : "启用"}`,
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          companyActive({
            id: record.id,
            active: record.status == "正常" ? 0 : 1,
          }).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        },
      });
    },
    tableSort(page, filters, { field, order }) {
      if (field == "balance") {
        this.sortString = order
          ? field + "," + (order == "descend" ? "desc" : "asc")
          : "";
        this.getList(1);
      }
    },
    cameltoLine(value) {
      return value.replace(/([A-Z])/g, "_$1").toLowerCase();
    },
    // 获取列表
    async getList(currentPage, currentSize) {
      this.loading = true;
      const { page, size, sortString } = this;

      let sort = sortString.split(",");
      this.searchForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            pageNum: currentPage || page,
            pageSize: currentSize || size,
            ...values,
            orders: [
              {
                column: this.cameltoLine(sort[0]),
                asc: sort[1] == "desc" ? false : true,
              },
            ],
          };
          const res = await capitalList(params);
          console.log('ssss',res)
          if (res?.success) {
            this.total = res?.data?.total || 0;
            this.dataSource = res?.data?.list || [];
          } else {
            this.$message.error(res?.message);
          }
          this.loading = false;
        } else {
          this.loading = false;
        }
      });
    },
    goFlowDetail({id}){
      this.$router.push({
        name:'FundInventory',
        query:{
          userId:id
        }
      })
    },
    showModal(type, record) {
      this.modalType = type;
      if (type == "add") {
        this.capitalId = "";
        this.editVisible = true;
        this.modalForm.resetFields();
      } else if (type == "edit") {
        let { id, name, balance, currencyType, allowArrearage,arrearageAmount,clientId } = record;
        this.capitalId = id;
        this.editVisible = true;
        this.$nextTick(() => {
          setTimeout(() => {
              this.modalForm.setFieldsValue({  name, balance, currencyType, allowArrearage:allowArrearage == 1 ?true:false,arrearageAmount,clientId})
          },400)
        })
      }else if(type == 'record'){
        this.capitalId = record.id
        this.addRecordVisible = true
      }
    },
    sureModal() {
      let { capitalId, modalType } = this;
      this.modalForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            ...values,
            id: capitalId,
            allowArrearage: values.allowArrearage?1:0,
          };
          console.log("params>>>", params);
          let res = modalType == 'add' ? await capitalAdd(params): await capitalEdit(params)
          if (res?.success) {
              this.$message.success(
                `${modalType == "add" ? "添加" : "编辑"}成功`
              );
              this.capitalId = "";
              this.editVisible = false;
              this.getList();
            } else {
              this.$message.error(res?.message);
            }
        }
      });
    },
    sureAddRecord(){
      let {capitalId} = this
      this.modalForm2.validateFields((err, values) => {
        if (!err) {
          let params = {
            ...values,
            capitalId,
            type:Number(values.type),
            operateTime: moment(values.operateTime).format('YYYY-MM-DD hh:mm:ss'),
          };
          console.log("params>>>", params);
          capitalAddRecord(params).then(res =>{
            console.log('jajajaj',res)
            if(res?.success){
              this.$message.success("添加成功");
              this.capitalId = "";
              this.addRecordVisible = false;
              this.getList();
            }else{
              this.$message.error(res?.message)
            }
          })
        }
      })
    }
  },
};
</script>
<style scoped>
:deep(.ant-calendar-picker) {
  width: 100% !important;
}
</style>
